import React, { Component, PropTypes } from 'react';
import ReactDOM from 'react-dom'
import Wrapper from '../wrapper';
import { ajax } from '../helper/helper';

XMLHttpRequest.prototype.sendAsBinary = function (file, param) {
	var formData = new FormData();
	formData.append('key', param.key);
	formData.append('token', param.token);
	formData.append('file', file);
	this.send(formData)
}

class SetProfile extends Component {
	constructor(props) {
		super(props);
		this.state = {
			username: user.name,
			email: user.email,
			oldPassword: '',
			newPassword: '',
			confirmPassword: '',
			profile_image: '',
			modifyPass: false,
			opacity: 0
		}
	}
	changeHandle(event) {
		let name = event.target.name;
		if (name == 'oldPassword') {
			this.setState({
				oldPassword: event.target.value
			});
		} else if (name == 'newPassword') {
			this.setState({
				newPassword: event.target.value
			});
		} else if (name == 'confirmPassword') {
			this.setState({
				confirmPassword: event.target.value
			});
		} else if (name == 'username') {
			this.setState({
				username: event.target.value
			});
		} else if (name == 'email') {
			this.setState({
				email: event.target.value
			});
		}

	}
	saveHandle(event) {
		event.preventDefault();
		var username = this.state.username,
			email = this.state.email,
			oldPassword = this.state.oldPassword,
			newPassword = this.state.newPassword,
			confirmPassword = this.state.confirmPassword,
			profile_image = this.state.profile_image,
			response_words = document.getElementById('response-words'),
			opacity = 1,
			data,
			url;

		let postData = { userName: username, email: email };


		if (oldPassword != '' && newPassword != '' && confirmPassword != '' && newPassword == confirmPassword) {
			url = '/settings/profile';

			ajax({
				url: url,
				type: 'POST',
				dataType: 'json',
				success: function (get_data) {
					data = JSON.parse(get_data);

					if (data.success) {
						response_words.innerHTML = '保存成功';

						this.setState({
							oldPassword: '',
							newPassword: '',
						});
					} else {
						response_words.innerHTML = data.error;
					}
				}.bind(this),
				error: function (status) { }.bind(this)

			});
		} else if (username != '' && email != '' && oldPassword == '' && newPassword == '') {

			url = '/settings/profile';
			var data = {
				name: username,
				email: email
			}
			if (profile_image != '') {
				data.profile_image = profile_image;
			}
			ajax({
				url: url,
				type: 'POST',
				dataType: 'json',
				data: data,
				success: function (get_data) {
					data = JSON.parse(get_data);
					if (data.success) {
						response_words.innerHTML = '保存成功';
						this.setState({
							oldPassword: '',
							newPassword: '',
						});
					}
				}.bind(this),
				error: function (status) { }.bind(this)
			});
		}

		let time = setInterval(() => {
			opacity -= 0.05;
			if (opacity <= 0) {
				clearInterval(time);
				response_words.innerHTML = '';
				this.setState({
					opacity: 0
				});
			} else {
				this.setState({
					opacity: opacity
				});
			}
		}, 100);

	}
	modifyPasswordHandle(e) {
		e.preventDefault();
		this.setState({
			modifyPass: !this.state.modifyPass
		});
	}
	changePicHandle(event) {
		var pic = document.getElementById('u-pic'),
			pic_file = pic.files[0],
			pic_name = pic_file.name,
			startIndex = pic_name.indexOf('.') + 1,
			pic_type = pic_name.substring(startIndex);
		this.getUploadParam(pic_type, function (data) {
			this.uploadFile(pic_file, data, this.uploadResult.bind(this));
		}.bind(this));

	}
	getUploadParam(type, callback) {
		var url = '/assets/request-token/' + type;
		if (!type) { callback(false) }

		ajax({
			url: url,
			type: 'GET',
			dataType: 'json',
			success: function (get_data) {
				var datas = JSON.parse(get_data);
				if (datas.success) {
					callback(datas.data);
				}
			}.bind(this),
			error: function () {
				callback(false);
			}.bind(this)

		});

	}
	uploadFile(file, param, callback) {
		var xhr = new XMLHttpRequest(),
			upload = xhr.upload;
		// if(progress){
		//     upload.addEventListener("progress", progress, false);
		// }
		xhr.open("POST", 'http://up.qiniu.com', true);
		xhr.sendAsBinary(file, param);
		xhr.onload = function () {
			if (xhr.responseText) {
				callback(xhr.responseText)
			}
		};
	}

	// validFileType(type,typeList){
	//     return _.contains(typeList,type)
	// }

	uploadResult(result) {

		var img_elem = document.getElementById('info-box').querySelector('img'),
			img_src = 'http://cdn2.parllay.cn/' + JSON.parse(result).key,
			url;
		img_elem.setAttribute('src', img_src);
		this.setState({
			profile_image: img_src
		});

	}
	render() {
		var saveHandle = this.saveHandle.bind(this),
			modifyPass = this.state.modifyPass,
			modifyPasswordHandle = this.modifyPasswordHandle.bind(this),
			username = this.state.username,
			email = this.state.email,
			oldPassword = this.state.oldPassword,
			newPassword = this.state.newPassword,
			confirmPassword = this.state.confirmPassword,
			opacity = this.state.opacity,
			changeHandle = this.changeHandle.bind(this),
			changePicHandle = this.changePicHandle.bind(this);

		return (
			<Wrapper currentPage="settings">
				<div className="setprofile">
					<div id="res-word">
						<div id="response-words" style={{ opacity: opacity }}>修改成功</div>
					</div>
					<div className="content-header setting-title">
						<h1>个人信息</h1>
					</div>
					{/* <div className="setting-title">个人信息</div> */}
					<div className="info-wrap">
						<div id="info-box">
							<form className="form-horizontal">
								<div className="form-group">
									<div className="col-sm-offset-2 col-sm-10">
										<label onChange={changePicHandle} htmlFor="u-pic" className="u-pic">
											<img src={`http://120.27.20.74:8080/face/pic/${user.profile_image}.jpg`} />
											<div className="u-pic-change">
												<input type="file" id="u-pic" />
												<span>替换头像</span>
												<span className="glyphicon glyphicon-paperclip"></span>
											</div>
										</label>
									</div>
								</div>
								<div className="form-group">
									<label htmlFor="username" className="col-sm-2 control-label">用户名</label>
									<div className="col-sm-10">
										<input tabIndex="1" onChange={changeHandle} value={username} type="text" className="form-control" name="username" id="username" />
										<span className="errorResetName" id="errorResetName"></span>
									</div>
								</div>
								<div className="form-group">
									<label htmlFor="email" className="col-sm-2 control-label">邮箱</label>
									<div className="col-sm-10">
										<input tabIndex="2" onChange={changeHandle} value={email} type="email" className="form-control" name="email" id="email" />
										<span className="errorResetEmail" id="errorResetEmail"></span>
									</div>
								</div>
								<div className="reset-pwd" id="modifyPass">
									<div className="content-header" style={{ paddingBottom: '12px', borderBottom: '1px solid #d0d6d9', marginBottom: 20 }}>
										<h1>修改密码</h1>
									</div>
									<p>修改密码需输入当前密码，新密码至少8位，建议定期更换密码，确保账号安全
									<button onClick={modifyPasswordHandle} className="btn btn-default btn-flat">
											{
												modifyPass ? '取消修改' : '修改密码'
											}
										</button>
									</p>


									<div className={modifyPass ? 'modifyPass' : 'nomodify'}>
										<div className="form-group">
											<label htmlFor="oldPass" className="col-sm-2 control-label">原密码</label>
											<div className="col-sm-10">
												<input tabIndex="3" onChange={changeHandle} type="password" value={oldPassword} name="oldPassword" className="form-control" id="oldPass" />
												<span className="errorOldPass"></span>
											</div>
										</div>
										<div className="form-group">
											<label htmlFor="newPass" className="col-sm-2 control-label">新密码</label>
											<div className="col-sm-10">
												<input tabIndex="4" onChange={changeHandle} type="password" value={newPassword} name="newPassword" className="form-control" id="newPass" />
												<span className="errorNewPass"></span>
											</div>
										</div>
										<div className="form-group">
											<label htmlFor="confirmNewPass" className="col-sm-2 control-label">确认密码</label>
											<div className="col-sm-10">
												<input tabIndex="5" onChange={changeHandle} type="password" value={confirmPassword} name="confirmPassword" className="form-control" id="confirmNewPass" disabled={newPassword.length ? false : true} />
												<span className="errorConfirmNewPass"></span>
											</div>
										</div>
									</div>
								</div>
								<div className="form-group">
									<div className="col-sm-offset-2 col-sm-10">
										<button id="save" onClick={saveHandle} type="submit" className="btn btn-primary btn-flat pull-right">保存</button>
									</div>
								</div>

							</form>
						</div>
					</div>
				</div>
			</Wrapper>
		);
	}

}

ReactDOM.render(
	<SetProfile />,
	document.getElementById('set')
);























